import router from './router'
import store from './store'

import { ElMessage } from 'element-plus'

import NProgress from 'nprogress' // progress bar 顶部经度条插件
import 'nprogress/nprogress.css' // progress bar style

import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  // 如果有token
  if (hasToken) {
    // console.log('hasToken', to)
    // 重定向到默认首页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        // 判断用户是否已通过getInfo获取权限角色
        // determine whether the user has obtained his permission roles through getInfo
        const hasRoles = store.getters.roles && store.getters.roles.length > 0

        // console.log(store.getters.roles)
        // 检测是否有store的用户权限
        if (hasRoles) {
          next()
        } else {
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          // 动态加载路由 有权限的路由添加到store
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            roles
          )

          for (let i = 0; i < accessRoutes.length; i++) {
            // 路由有些忘记添加 / 这里做补充 防止异常
            if (!accessRoutes[i].path.startsWith('/')) {
              accessRoutes[i].path = `/${accessRoutes[i].path}`
            }

            router.addRoute(accessRoutes[i])
          }

          // router.addRoutes(accessRoutes) // 此方法在3.x版本可以添加多个，新版只能循环添加

          // console.log(router)
          // console.log(accessRoutes)   // 获取的路由总数
          // console.log(router.getRoutes()) // 查看当前路由
          next({ ...to, replace: true })
        }
      } catch (error) {
        await store.dispatch('user/resetToken')
        ElMessage.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    /* miss token*/
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
